package com.datas.utils.hbn;

import com.datas.db.hibernatebeans.UmsSysLog;
import com.datas.utils.JigeWebTools;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.LoggerFactory;

/**
 * Created by jige0727 on 2017/5/16.
 * hibernate 执行器
 * 如果有日志对象 则插入日志
 */
public abstract class HbnTxRuner {
    @Getter
    Session currentSession;
    @Getter
    @Setter
    UmsSysLog sys_log = null;

    protected abstract Object dataLogic() throws Exception;

    /**
     * 执行 带事务
     *
     * @return
     */
    public Object runTx() {
        SessionFactory sessionFactory = JigeWebTools.appContext.getBean(SessionFactory.class);
        currentSession = sessionFactory.openSession();
        currentSession.beginTransaction();
        Object res = null;
        try {
            res = dataLogic();
            currentSession.getTransaction().commit();
            if (sys_log != null) {
                sys_log.setActResult(UmsSysLog.LOG_RESULT_SUCCESS);
            }
        } catch (Exception e) {
            res = null;
            currentSession.getTransaction().rollback();
            LoggerFactory.getLogger(getClass()).info("error -> ", e);
            if (sys_log != null) {
                sys_log.setActResult(UmsSysLog.LOG_RESULT_FAIL);
            }
        } finally {
            if (sys_log != null) {
                getCurrentSession().save(sys_log);
            }
            currentSession.close();
        }
        return res;
    }

    /**
     * 执行 不带事务
     *
     * @return
     */
    public Object run() {
        SessionFactory sessionFactory = JigeWebTools.appContext.getBean(SessionFactory.class);
        currentSession = sessionFactory.openSession();
        Object res = null;
        try {
            res = dataLogic();
            if (sys_log != null) {
                sys_log.setActResult(UmsSysLog.LOG_RESULT_SUCCESS);
            }
        } catch (Exception e) {
            res = null;
            LoggerFactory.getLogger(getClass()).info("error -> ", e);
            if (sys_log != null) {
                sys_log.setActResult(UmsSysLog.LOG_RESULT_FAIL);
            }
        } finally {
            if (sys_log != null) {
                getCurrentSession().save(sys_log);
            }
            currentSession.close();
        }
        return res;
    }
}
